<?php
/**
 * @version 0.8.3 2010-10-07
 * @package Joomla
 * @subpackage LeagueResults
 * @copyright (C)  2008, 2009, 2010 Henryk Drozd
 * @license GNU/GPL, see LICENSE.php
 * LeagueResults is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 2
 * as published by the Free Software Foundation.

 * LeagueResults is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class lrModelTablecontents extends JModel
{
	var $_data = null;
	var $_total = null;
	var $_pagination = null;
	function __construct()
	{
		parent::__construct();

		global $mainframe, $option;

		$limit		= $mainframe->getUserStateFromRequest( $option.'limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $mainframe->getUserStateFromRequest( $option.'limitstart', 'limitstart', 0, 'int' );

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);

	}
	
	/**
	* Load a list of database objects after succesful queryBatch method
	*
	* If <var>key</var> is not empty then the returned array is indexed by the value
	* the database key.  Returns <var>null</var> if the query fails.
	*
	* @access	public
	* @param string The field name of a primary key
	* @return array If <var>key</var> is empty as sequential list of returned records.
	*/
	function loadObjectList4Batch( $key='' )
	{
		if (!($cur = $this->_db->_cursor)) {
			return null;
		}
		$array = array();
		while ($row = mysql_fetch_object( $cur )) {
			if ($key) {
				$array[$row->$key] = $row;
			} else {
				$array[] = $row;
			}
		}
		mysql_free_result( $cur );
		return $array;
	}
	
	 
	function getData()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
			$this->_data = $this->_additionals($this->_data);
		}
//		if ( true) {echo $query.'<br>';print_r ($document);};

		return $this->_data;
	}
	
	function &getTableheaders()
	{
		$query = 'SELECT id AS value, tname AS text'
				. ' FROM #__lr_tableheaders'
				. ' WHERE published = 1'
				;

		$this->_db->setQuery( $query );

		$this->_tableheaders = $this->_db->loadObjectList();
		
		return $this->_tableheaders;
	}
	
	function &getSeasons()
	{
		$query = 'SELECT id AS value, CONCAT(CONCAT(name," "), year) AS text'
				. ' FROM #__lr_leagueseasons'
				. ' WHERE published = 1'
				;

		$this->_db->setQuery( $query );

		$this->_seasons = $this->_db->loadObjectList();
//		print_r($this->_seasons);
		return $this->_seasons;
	}

	function getTotal()
	{
		// Lets load the total nr if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}


	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}

	function _buildQuery()
	{
		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildContentWhere();
		$orderby	= $this->_buildContentOrderBy();

		$query = 'SELECT  tc.*, th.leagueseasons_id, s.name, th.tname, th.tdate, 
						th.pointsformat, t.tablename, t.tbadge						
					FROM #__lr_tablecontents AS tc
					JOIN #__lr_tableheaders AS th ON th.id = tc.tableheaders_id
					JOIN #__lr_teams AS t ON tc.team_id = t.id				
					JOIN #__lr_leagueseasons AS s ON th.leagueseasons_id = s.id
					'
					. $where
					. $orderby
					;

//echo $query;

		return $query;
		
	}

	/**
	 * Build the order clause
	 *
	 * @access private
	 * @return string
	 */
	function _buildContentOrderBy()
	{
		global $mainframe, $option;

		$filter_order		= $mainframe->getUserStateFromRequest( $option.'.tablecontents.filter_order', 'filter_order', 'tc.id DESC', 'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'.tablecontents.filter_order_Dir', 'filter_order_Dir', '', 'word' );

		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
		//$orderby = '';
		//echo $orderby;
		return $orderby;
	}

	function _buildContentWhere()
	{
		global $mainframe, $option;

		$filter_state 		= $mainframe->getUserStateFromRequest( $option.'.filter_state', 'filter_state', '', 'word' );
		$leagueseasons_id 	= $mainframe->getUserStateFromRequest( $option.'.leagueseasons_id', 'leagueseasons_id', '', 'int' );
		$table_id 	= $mainframe->getUserStateFromRequest( $option.'.table_id', 'table_id', '', 'int' );
		
		$filter 			= $mainframe->getUserStateFromRequest( $option.'.filter', 'filter', '', 'int' );
		$search 			= $mainframe->getUserStateFromRequest( $option.'.search', 'search', '', 'string' );
		$search 			= $this->_db->getEscaped( trim(JString::strtolower( $search ) ) );

		$where = array();
		if ($leagueseasons_id) {	
			$where[] = 'th.leagueseasons_id = '.$leagueseasons_id;
		}
		if ($table_id) {	
			$where[] = 'tc.tableheaders_id = '.$table_id;
		}
		if ($filter_state) {
			if ($filter_state == 'P') {
				$where[] = 'tc.published = 1';
			} else if ($filter_state == 'U') {
				$where[] = 'tc.published = 0';
			} else {
				$where[] = 'tc.published >= 0';
			}
		} else {
			$where[] = 'tc.published >= 0';
		}

		if ($search && $filter == 1) {
			$where[] = ' LOWER(t.tablename) LIKE \'%'.$search.'%\' ';
		}
		if ($search && $filter == 2) {
			$where[] = ' LOWER(th.tname) LIKE \'%'.$search.'%\' ';
		}
		if ($search && $filter == 3) {
			$where[] = ' th.tdate =\''.$search.'\' ';
		}

		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );

		return $where;
	}

	function _additionals($rows)
	{
		/*for ($i=0, $n=count($rows); $i < $n; $i++) {

			// count registered users
			$query = 'SELECT count(r.event)'
					. ' FROM #__eventlist_register AS r'
					. ' WHERE r.event = '.$rows[$i]->id
					;
			$this->_db->SetQuery( $query );

			$rows[$i]->regCount = $this->_db->loadResult();

			// Get editor name
			$query = 'SELECT name'
					. ' FROM #__users'
					. ' WHERE id = '.$rows[$i]->modified_by
					;
			$this->_db->SetQuery( $query );

			$rows[$i]->editor = $this->_db->loadResult();
		}
*/
		return $rows;
	}

	function publish($cid = array(), $publish = 1)
	{
		$user 	=& JFactory::getUser();
		$userid = (int) $user->get('id');

		if (count( $cid ))
		{
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__lr_tablecontents'
				. ' SET published = '. (int) $publish
				. ' WHERE id IN ('. $cids .')'
				;
			$this->_db->setQuery( $query );

			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}
	}

	function delete($cid = array())
	{
		$result = false;

		if (count( $cid ))
		{
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM #__lr_tablecontents'
					. ' WHERE id IN ('. $cids .')'
					;

			$this->_db->setQuery( $query );

			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}
	
	function multicopy($cids = array())
	{
		if (0 == JRequest::getVar( 'table_id')){
			return 0;
		}
	
		$row  =& $this->getTable('lr_tablecontents', '');
		
	
		foreach ($cids as $tposition)
		{
		$row->load($tposition);
		$row->tableheaders_id	= JRequest::getVar( 'table_id');
		$row->id = null;
		// Store it in the db
		if (!$row->store()) {
			JError::raiseError(500, $this->_db->getErrorMsg() );
			return false;
			}
		}
		
		return count($cids);
	}
	
	function autocreatetable($s, $t, $d, $p)
	{
	$row  =& $this->getTable('lr_tableheaders', '');
	$row->id = null;
	$row->leagueseasons_id = $s;
	$row->tname = $t;
	$row->tdate = $d;
	$row->published = $p;
	
	$pf = & $this->getTable('lr_leagueseasons', '');
    $pf->load($s);
    
    $row->pointsformat = $pf->seasonpointsformat;
	
	// Store it in the db
	if (!$row->store()) {
		JError::raiseError(500, $this->_db->getErrorMsg() );
		return false;
		}
	
	if (!$this->createtablepositions($row->id))
    	return false;
    	
    return true;
	}
	
	
	function createtablepositions($tid)
	{
	$prequery = "SELECT pl.* 
					FROM #__lr_tableheaders AS th 
					JOIN #__lr_leagueseasons AS s ON s.id = th.leagueseasons_id
					JOIN #__lr_pointslogic AS pl ON pl.pointslogictype = s.pointslogictype
					WHERE th.id = ".$tid; 
					
		$this->_db->setQuery( $prequery );

		$this->_standingsorder = $this->_db->loadObject();
		
	$theader = & $this->getTable('lr_tableheaders', '');
    $theader->load($tid);
    
	$query = "SET @pos := 0;SELECT @pos :=@pos+1 AS position, t.teamid, 
     sum( CASE WHEN f0.hscore > f0.vscore AND f0.hteam_id = t.teamid THEN pts4win
               WHEN f0.hscore = f0.vscore AND f0.hteam_id = t.teamid THEN pts4draw
               WHEN f0.hscore < f0.vscore AND f0.hteam_id = t.teamid THEN pts4lost
               WHEN f0.hscore < f0.vscore AND f0.vteam_id = t.teamid THEN pts4win
               WHEN f0.hscore = f0.vscore AND f0.vteam_id = t.teamid THEN pts4draw
               WHEN f0.hscore > f0.vscore AND f0.vteam_id = t.teamid THEN pts4lost
          ELSE 0 END) AS points,

     sum(CASE WHEN f0.hteam_id = t.teamid THEN 1 ELSE 0 END) AS hmatches, 
     sum( CASE WHEN f0.hscore > f0.vscore AND f0.hteam_id = t.teamid THEN pts4win
               WHEN f0.hscore = f0.vscore AND f0.hteam_id = t.teamid THEN pts4draw
               WHEN f0.hscore < f0.vscore AND f0.hteam_id = t.teamid THEN pts4lost
          ELSE 0 END) AS hpoints,
     sum( CASE WHEN f0.hscore > f0.vscore AND f0.hteam_id = t.teamid THEN 1 ELSE 0 END) AS hwins,
     sum( CASE WHEN f0.hscore = f0.vscore AND f0.hteam_id = t.teamid THEN 1 ELSE 0 END) AS hdraws,
     sum( CASE WHEN f0.hscore < f0.vscore  AND f0.hteam_id = t.teamid THEN 1 ELSE 0 END) AS hdefeats, 
     sum(CASE WHEN f0.hteam_id = t.teamid THEN f0.hscore ELSE 0 END) AS hscoreplus, 
     sum(CASE WHEN f0.hteam_id = t.teamid THEN f0.vscore ELSE 0 END) AS hscoreminus,

     sum(CASE WHEN f0.vteam_id = t.teamid THEN 1 ELSE 0 END) AS amatches, 
     sum( CASE WHEN f0.hscore < f0.vscore AND f0.vteam_id = t.teamid THEN pts4win
               WHEN f0.hscore = f0.vscore AND f0.vteam_id = t.teamid THEN pts4draw
               WHEN f0.hscore > f0.vscore AND f0.vteam_id = t.teamid THEN pts4lost
          ELSE 0 END) AS apoints,

     sum( CASE WHEN f0.hscore < f0.vscore AND f0.vteam_id = t.teamid THEN 1 ELSE 0 END) AS awins,
     sum( CASE WHEN f0.hscore = f0.vscore AND f0.vteam_id = t.teamid THEN 1 ELSE 0 END) AS adraws,
     sum( CASE WHEN f0.hscore > f0.vscore  AND f0.vteam_id = t.teamid THEN 1 ELSE 0 END) AS adefeats, 

     sum(CASE WHEN f0.vteam_id = t.teamid THEN f0.vscore ELSE 0 END) AS ascoreplus, 
     sum(CASE WHEN f0.vteam_id = t.teamid THEN f0.hscore ELSE 0 END) AS ascoreminus,
     sum(CASE WHEN f0.vteam_id = t.teamid THEN f0.vscore-f0.hscore
     		WHEN f0.hteam_id = t.teamid THEN f0.hscore-f0.vscore 
     		ELSE 0 END) AS scorediff, 
     sum( CASE 
     		WHEN f0.hscore < f0.vscore AND f0.vteam_id = t.teamid THEN 1
     		WHEN f0.hscore > f0.vscore AND f0.hteam_id = t.teamid THEN 1 
     		ELSE 0 END)/
     sum( CASE 
     		WHEN f0.vteam_id = t.teamid THEN 1
     		WHEN f0.hteam_id = t.teamid THEN 1 
     		ELSE 0 END)
     		AS winsavrg,
     		sum( CASE 
     				WHEN f0.vteam_id = t.teamid THEN f0.vscore
     				WHEN f0.hteam_id = t.teamid THEN f0.hscore
     				ELSE 0 END)/
     		sum( CASE 
     				WHEN f0.vteam_id = t.teamid THEN f0.hscore
     				WHEN f0.hteam_id = t.teamid THEN f0.vscore
     				ELSE 0 END)
     		AS scoreavrg
     		
     				
FROM (SELECT hteam_id AS teamid FROM jos_lr_fixtures UNION SELECT vteam_id FROM jos_lr_fixtures) AS t 
  JOIN jos_lr_fixtures AS f0 ON (t.teamid = f0.hteam_id OR t.teamid = f0.vteam_id)
  JOIN jos_lr_leagueseasons AS s ON f0.leagueseasons_id = s.id 
  JOIN jos_lr_pointslogic AS pl ON s.pointslogictype = pl.pointslogictype 
WHERE f0.results_quantity > 0   
	AND f0.leagueseasons_id = ".$theader->leagueseasons_id." AND f0.matchdate <= '".$theader->tdate."'
GROUP BY teamid, pl.pointslogictype ";
//1st rule
switch ($this->_standingsorder->pos1strule){
	case 'points':
		$query .= 'ORDER BY points DESC ';
		break;
	case 'wins':
		$query .= 'ORDER BY winsavrg DESC ';
		break;
	default:
		$query .= 'ORDER BY points DESC ';
		break;
	}

//2nd rule
switch ($this->_standingsorder->pos2ndrule){
	case 'allscore':
		$query .= ', scorediff DESC ';
		break;
	case 'allscoreavrg':
		$query .= ', scoreavrg DESC ';
		break;
	default:
	}
	
		//echo $query;

		$this->_db->setQuery( $query );
		$this->_db->queryBatch();
		
		$this->_tablepositions = $this->loadObjectList4Batch();
// Positions adjustments
		switch ($this->_standingsorder->pos2ndrule){
			case 'directscore':
				$this->sorttablepositions($theader->leagueseasons_id, $theader->tdate);
				break;
			default:
				break;
		}
		
		$row  =& $this->getTable('lr_tc_homeaway', '');
		$rowx  =& $this->getTable('lr_tablecontents', '');
		$row_num = 1;
		foreach ($this->_tablepositions as $tposition)
		{
		$row->tableheaders_id = $tid;
		$row->team_id = $tposition->teamid;
		$row->hmatches = $tposition->hmatches;
		$row->hpoints = $tposition->hpoints;
		$row->hwins = $tposition->hwins;
		$row->hdraws = $tposition->hdraws;
		$row->hdefeats = $tposition->hdefeats;
		$row->hscoreplus = $tposition->hscoreplus;
		$row->hscoreminus = $tposition->hscoreminus;
		$row->amatches = $tposition->amatches;
		$row->apoints = $tposition->apoints;
		$row->awins = $tposition->awins;
		$row->adraws = $tposition->adraws;
		$row->adefeats = $tposition->adefeats;
		$row->ascoreplus = $tposition->ascoreplus;
		$row->ascoreminus = $tposition->ascoreminus;
		
		$row->id = null;
		$rowx->id = null;
		$rowx->published = 1;
		
		$rowx->tableheaders_id = $tid;
		$rowx->team_id = $tposition->teamid;
		$rowx->position = $tposition->position;
		$rowx->matches = $tposition->hmatches+$tposition->amatches;
		$rowx->points = $row->hpoints+$row->apoints;
		$rowx->wins = $tposition->hwins+$tposition->awins;
		$rowx->draws = $tposition->hdraws+$tposition->adraws;
		$rowx->defeats = $tposition->hdefeats+$tposition->adefeats;
		$rowx->scoreplus = $tposition->hscoreplus+$tposition->ascoreplus;
		$rowx->scoreminus = $tposition->hscoreminus+$tposition->ascoreminus;
		
		// Store it in the db
		if (!$row->store()) {
			JError::raiseError(500, $this->_db->getErrorMsg() );
			return false;
			}
		if (!$rowx->store()) {
			JError::raiseError(500, $this->_db->getErrorMsg() );
			return false;
			}
			
		}
	return true;
	}
	function sorttablepositions($sid, $tdate)
	{
	$tobesolved = array();
	//1st create the list of 'small tables'
	//2nd solve the positions inside 'small tables'
	//3rd update the positions inside _tablepositions

	//1st
		$previous = -1;
		foreach ($this->_tablepositions as $tp)
			{
			switch ($this->_standingsorder->pos1strule){
				case 'points':
					if ($previous <> $tp->points)
						$previous = $tp->points;
					else 
						{
						//catch all positions with this value of points if not cought already
						if (!isset($tobesolved[$previous])){
							foreach ($this->_tablepositions as $_tp){
								if ($_tp->points == $previous)
									$tobesolved[$previous][] = $_tp;
								}
							}
						}
					break;
				case 'wins':
					if ($previous <> $tp->winsavrg)
						$previous = $tp->winsavrg;
					else 
						{
						//catch all positions with this value of points if not cought already
						if (!isset($tobesolved[(string)$previous])){
							foreach ($this->_tablepositions as $_tp){
								if ($_tp->winsavrg == $previous)
									$tobesolved[(string)$previous][] = $_tp;
								}
							}
						}
					break;
				default:
					break;
				}
			}
		foreach ($tobesolved as $thesame){
			$inexpression = '';
			foreach ($thesame as $one){
				if ($inexpression == '')
					$inexpression = '('.$one->teamid;
				else
					$inexpression .= ','.$one->teamid;
			}
			$inexpression .= ')';
		
		$secondquery = "SET @pos := 0;SELECT @pos :=@pos+1 AS position, t.teamid, 
		     sum( CASE WHEN f0.hscore > f0.vscore AND f0.hteam_id = t.teamid THEN pts4win
		               WHEN f0.hscore = f0.vscore AND f0.hteam_id = t.teamid THEN pts4draw
		               WHEN f0.hscore < f0.vscore AND f0.hteam_id = t.teamid THEN pts4lost
		               WHEN f0.hscore < f0.vscore AND f0.vteam_id = t.teamid THEN pts4win
		               WHEN f0.hscore = f0.vscore AND f0.vteam_id = t.teamid THEN pts4draw
		               WHEN f0.hscore > f0.vscore AND f0.vteam_id = t.teamid THEN pts4lost
		          ELSE 0 END) AS points,
		
		     sum(CASE WHEN f0.hteam_id = t.teamid THEN 1 ELSE 0 END) AS hmatches, 
		     sum( CASE WHEN f0.hscore > f0.vscore AND f0.hteam_id = t.teamid THEN pts4win
		               WHEN f0.hscore = f0.vscore AND f0.hteam_id = t.teamid THEN pts4draw
		               WHEN f0.hscore < f0.vscore AND f0.hteam_id = t.teamid THEN pts4lost
		          ELSE 0 END) AS hpoints,
		     sum( CASE WHEN f0.hscore > f0.vscore AND f0.hteam_id = t.teamid THEN 1 ELSE 0 END) AS hwins,
		     sum( CASE WHEN f0.hscore = f0.vscore AND f0.hteam_id = t.teamid THEN 1 ELSE 0 END) AS hdraws,
		     sum( CASE WHEN f0.hscore < f0.vscore  AND f0.hteam_id = t.teamid THEN 1 ELSE 0 END) AS hdefeats, 
		     sum(CASE WHEN f0.hteam_id = t.teamid THEN f0.hscore ELSE 0 END) AS hscoreplus, 
		     sum(CASE WHEN f0.hteam_id = t.teamid THEN f0.vscore ELSE 0 END) AS hscoreminus,
		
		     sum(CASE WHEN f0.vteam_id = t.teamid THEN 1 ELSE 0 END) AS amatches, 
		     sum( CASE WHEN f0.hscore < f0.vscore AND f0.vteam_id = t.teamid THEN pts4win
		               WHEN f0.hscore = f0.vscore AND f0.vteam_id = t.teamid THEN pts4draw
		               WHEN f0.hscore > f0.vscore AND f0.vteam_id = t.teamid THEN pts4lost
		          ELSE 0 END) AS apoints,
		
		     sum( CASE WHEN f0.hscore < f0.vscore AND f0.vteam_id = t.teamid THEN 1 ELSE 0 END) AS awins,
		     sum( CASE WHEN f0.hscore = f0.vscore AND f0.vteam_id = t.teamid THEN 1 ELSE 0 END) AS adraws,
		     sum( CASE WHEN f0.hscore > f0.vscore  AND f0.vteam_id = t.teamid THEN 1 ELSE 0 END) AS adefeats, 
		
		     sum(CASE WHEN f0.vteam_id = t.teamid THEN f0.vscore ELSE 0 END) AS ascoreplus, 
		     sum(CASE WHEN f0.vteam_id = t.teamid THEN f0.hscore ELSE 0 END) AS ascoreminus,
		     sum(CASE WHEN f0.vteam_id = t.teamid THEN f0.vscore-f0.hscore
		     		WHEN f0.hteam_id = t.teamid THEN f0.hscore-f0.vscore 
		     		ELSE 0 END) AS scorediff, 
		     sum( CASE 
		     		WHEN f0.hscore < f0.vscore AND f0.vteam_id = t.teamid THEN 1
		     		WHEN f0.hscore > f0.vscore AND f0.hteam_id = t.teamid THEN 1 
		     		ELSE 0 END)/
		     sum( CASE 
		     		WHEN f0.vteam_id = t.teamid THEN 1
		     		WHEN f0.hteam_id = t.teamid THEN 1 
		     		ELSE 0 END)
		     		AS winsavrg,
		     		sum( CASE 
		     				WHEN f0.vteam_id = t.teamid THEN f0.vscore
		     				WHEN f0.hteam_id = t.teamid THEN f0.hscore
		     				ELSE 0 END)/
		     		sum( CASE 
		     				WHEN f0.vteam_id = t.teamid THEN f0.hscore
		     				WHEN f0.hteam_id = t.teamid THEN f0.vscore
		     				ELSE 0 END)
		     		AS scoreavrg
		FROM (SELECT hteam_id AS teamid FROM jos_lr_fixtures UNION SELECT vteam_id FROM jos_lr_fixtures) AS t 
		  JOIN jos_lr_fixtures AS f0 ON ((t.teamid = f0.hteam_id OR t.teamid = f0.vteam_id) 
		  		AND f0.hteam_id IN ".$inexpression."
		  		AND f0.vteam_id IN ".$inexpression.")
		  JOIN jos_lr_leagueseasons AS s ON f0.leagueseasons_id = s.id 
		  JOIN jos_lr_pointslogic AS pl ON s.pointslogictype = pl.pointslogictype 
		WHERE f0.results_quantity > 0 
			AND f0.leagueseasons_id = ".$sid." AND f0.matchdate <= '".$tdate."'
		GROUP BY teamid, pl.pointslogictype 
		ORDER BY points DESC, scoreavrg DESC";
//		echo '<br/><br/>'.$secondquery;
				$this->_db->setQuery( $secondquery );
				$this->_db->queryBatch();
				$this->_smalltablepositions = $this->loadObjectList4Batch();

			unset($first);
			foreach ($thesame as $team2move){
				foreach($this->_tablepositions as $tcorginal){
					if ($tcorginal->teamid != $team2move->teamid)
						continue;
					if (!isset($first)){$first = $tcorginal->position;}
					foreach ($this->_smalltablepositions as $smalltbl){
						if ($smalltbl->teamid != $team2move->teamid)
							continue;
						$tcorginal->position = $first + $smalltbl->position - 1;
							
						}
					}
				}
				
		}
    return true;
	}
}//Class end
?>